<?php
namespace control;
/*
*考试记录类
*/
class examRecordClass extends adIndexClass
{
    private const page = 'examRecord';
    private const table = 'topic_answer_record';
    private const title = '考试记录';

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('topic.table.testStart') => text(["name" => "createTime", 'laydate' => [ 'range' => '~'] ]),
                    L('recruitment.table.state')     => select(array("name" => "state","option" => array("合格","不合格"))),
                    L('staffProfiles.table.department') => selectMultiple(["name" => "departmentId", 'table' => " department", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200']),
                ],
                [
                    L('topic.table.paperName')   => text(array("name" => "title")),
                    L('staffProfiles.table.name')   => text(array("name" => "name")),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*财务管理-收支平衡-列表页-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        $button = "<span class='spanButton' onclick=\"layer('".self::page."','statistics',{})\">".L('topic.table.statisticalChart')."</span>";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'startTime'      => [
                        'name'  => L('topic.table.testStart'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'paperName' => [
                        'name'  => L('topic.table.paperName'),
                        'width' => 200,
                    ],
                    'department'  => [
                        'name'  =>  L('staffProfiles.table.department'),
                        'width' => 200,
                    ],
                    'job'         => [
                        'name'  => L('staffProfiles.table.job'),
                        'width' => 200,
                    ],
                    'name'          => [
                        'name'  => L('staffProfiles.table.name'),
                        'width' => 200,
                    ],
                    'totalScore'          => [
                        'name'  => L('topic.table.paperScore'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'score'          => [
                        'name'  => L('topic.table.examScore'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => L('recruitment.table.state'),
                        'width' => 150,
                    ],
                ];
        }
        return $tr;
    }

    /*财务管理-收支平衡-列表页-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "name" => $this->post('name'),//姓名
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),   //状态
            "isCommit"      =>1,        //已提交试卷的
        );
        $and = '';
        if ($this->post('createTime')) {
            $timeArr = explode(' ~ ', $this->post('createTime'));
            $and .= " and date(startTime) >='{$timeArr[0]}' and date(startTime) <='{$timeArr[1]}'";
        }
        if (!empty($this->post('departmentId'))){
            //部门
            $and.=" and jobId in (select id from job where departmentId = '{$this->post('departmentId')}')";
        }
        if (!empty($this->post('title'))){
            //部门
            $and.=" and paperId in (select id from `paper_library` where name like '%{$this->post('title')}%')";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'startTime desc,time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(["like" => $like,"=" => $equal]).$and;
        $page = $this->page(array("table" => self::table, "where" => $where,"order" => $orderBy['orderBy']));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array("");
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = "<span onclick=\"window.open('" . root . "control/adIndex.html?cla=paperManagement&fun=previewPaper&method=record&stid={$array['stid']}&id={$array['paperId']}')\"><img src='".root."img/control/preview.svg' class='listIco'></span>";
            $liButton[] = $dominate;
            //数据准备
            $job = query('job', " id = '$array[jobId]'");
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "paperName":
                        $paper = query('paper_library'," id = '$array[paperId]'");
                        $row[] = $paper['name'];
                        break;
                    case "department":
                        $department = query('department', " id = '$job[departmentId]'");
                        $row[] = $department['name'];
                        break;
                    case "job":
                        $row[] = $job['name'];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'].$button."<form name='listForm'>".$li."</form>".$page['button'];
        $json['html'].=<<<eof
        <script src='{$this->root}static/javascript/echarts.min.js'></script>
		<script src='{$this->root}static/javascript/echarts.style.js'></script>
<script>

/**
 * 折线图
 * @param id DIV ID
 * @param name 图形名称
 * @param xAxis_data X轴数据
 * @param series_data Y轴数据
 */
function lineCharts(id, name, xAxis_data, series_data) {
    var myChart = echarts.init(document.getElementById(id));
    var option = {
        title: {
            text: name,
        },
      
        xAxis: {
            type: 'category',
            data: xAxis_data
        },
        tooltip: {
            show: true
        },
        yAxis: [{
            type: 'value',

        }],
        series: [{
            data: series_data,
            type: 'line',
        }]
    };
    // 指定图表的配置项和数据
    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);
}
</script>
eof;

        return json_encode($json, 320);
    }
    /*统计图*/
    public function statistics()
    {
        $text =selectMultiple(array('table'=>"staff",'name'=>'stid','sqlId'=>'stid','sqlField'=>'name','title'=>L('topic.table.staff')));
        $searchButton=L('topic.table.searchButton');
        $html = <<<efo
<div class="search">{$text}<input class="searchSub" onclick="searchLine()" type="button" value="$searchButton"></div>
<div id="main" style="width: 950px;height:450px;"></div>
<script>
 $(function() {
   searchLine();
 })

 function searchLine(){
     let stid = $("[name='stid']").val();
     $.post(root+'control/adIndex.html?cla=examRecord&fun=searchLine',{stid:stid},function(res) {
       lineCharts('main','',res.data.xData,res.data.yData);
     },'json')
 }
</script>
efo;
        return $this->layer(array("title" =>L('topic.table.statisticalChart'),"height" => 550,"width" => 1000,"html" => $html,"button" => false));
    }

    public function searchLine(){
        $stid = $this->post('stid');
        $xData = $yData = [];
        $result = find(array('table'=>'topic_answer_record','where'=>"isCommit = 1 and stid = '$stid'"));
        foreach ($result['array'] as $index =>$array){
            $xData[] = str_replace(['{{i}}'],[$index+1],L('topic.table.searchLine'));
            $yData[] = $array['score'];
        }
        $json['data'] = ['xData'=>$xData,'yData'=>$yData];
        return json_encode($json,320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = L('staffProfiles.tip.permission_export_warn');
        }  else {
            $data = [];
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            if (!self::is_null_array($checkedId)){
                $result = find(array("table" => self::table, "where" => "id in ('".implode("','", $checkedId)."') order by startTime desc,time desc"))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            foreach ($result as $array){
                $column = [];
                $job = query('job', " id = '$array[jobId]'");
                $department = query('department', " id = '$job[departmentId]'");
                $paper = query('paper_library'," id = '$array[paperId]'");
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '考试开始时间'=>$array['startTime'],
                            '试卷标题'=> $paper['name'],
                            '部门'=>$department['name'],
                            '职位'=>$job['name'],
                            '姓名'=>$array['name'],
                            '试卷总分'=>$array['totalScore'],
                            '考试得分'=>$array['score'],
                            '状态'=>$array['state'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = str_replace(['{{staffName}}'],[$this->control['name']],L('topic.table.examRecordExport'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, L('topic.table.examRecord').".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'考试开始时间',
                    'aliasName'=>'考试开始时间',
                ],
                [
                    'columnName'=>'试卷标题',
                    'aliasName'=>'试卷标题',
                ],
                [
                    'columnName'=>'部门',
                    'aliasName'=>'部门',
                ],
                [
                    'columnName'=>'职位',
                    'aliasName'=>'职位',
                ],
                [
                    'columnName'=>'姓名',
                    'aliasName'=>'姓名',
                ],
                [
                    'columnName'=>'试卷总分',
                    'aliasName'=>'试卷总分',
                ],
                [
                    'columnName'=>'考试得分',
                    'aliasName'=>'考试得分',
                ],
                [
                    'columnName'=>'状态',
                    'aliasName'=>'状态',
                ],
            ]
        };
    }
}
